<template>
	<view class="list">
		<view class="cu-bar search bg-white">
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input :adjust-position="false" type="text" v-model="query" placeholder="搜索书名、作者" confirm-type="search"></input>
			</view>
			<view class="action">
				<button class="cu-btn bg-green shadow-blur round main-btn"  @click="search">搜索</button>
				<button class="cu-btn bg-blue shadow-blur round" v-if="isAdmin" @click="gotoAddBooks">添加书籍</button>
			</view>
		</view>
		<!-- 刷新页面后的顶部提示框 -->
		<!-- 当前弹出内容没有实际逻辑 ，可根据当前业务修改弹出提示 -->
		<view class="tips" :class="{ 'tips-ani': tipShow }">为您更新了10条本书籍</view>
		<uni-clientdb ref="udb" v-slot:default="{data, loading, error, options}" :options="formData" :collection="collection"
		 :field="field" @load="load" :where="where" orderby="order_count desc">
			<!-- 基于 uni-list 的页面布局 -->
			<uni-list class="uni-list--waterfall">
				<!-- to 属性携带参数跳转详情页面，当前只为参考 -->
				<uni-list-item :border="false" class="uni-list-item--waterfall" title="图书列表" v-for="item in data" :key="item._id" :to="'../detail/detail?book_id='+item.book_id+'&title='+item.title">
					<!-- 通过header插槽定义列表左侧图片 -->
					<template v-slot:header>
						<view class="uni-thumb shop-picture shop-picture-column">
							<image :src="item.book_thumb" mode="heightFix"></image>
							<view class="order_icon" v-if="item.ordered">
								<text class="text">已借阅</text>
							</view>
						</view>
					</template>
					<!-- 通过body插槽定义商品布局 -->
					<view slot="body" class="shop">
						<view>
							<view class="uni-title">
								<text class="uni-ellipsis-2">{{ item.title }}</text>
							</view>
							<view>
								<text class="text-sm">{{ item.author }}</text>
								<text v-for="tag in item.tag" :key="tag" class="uni-tag">{{ tag }}</text>
							</view>
						</view>
						<view>
							<view class="uni-note">借阅次数 {{ item.order_count }}</view>
						</view>
					</view>
				</uni-list-item>
			</uni-list>
			<!-- 通过 loadMore 组件实现上拉加载效果，如需自定义显示内容，可参考：https://ext.dcloud.net.cn/plugin?id=29 -->
			<uni-load-more v-if="loading || options.status === 'noMore' " :status="options.status" />
		</uni-clientdb>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const dbSearchFields = ['title', 'author'];
	const app = getApp();
	import shareMsg from '@/common/shareMessage.js';
	
	export default {
		components: {},
		data() {
			return {
				// 数据表名
				collection: 'library-books',
				// 查询字段，多个字段用 , 分割
				field: '_id,title,book_thumb,author,publishing_house,ISBN,description,ordered,order_count,book_id',
				formData: {
					status: 'loading', // 加载状态
				},
				tipShow: false ,// 是否显示顶部提示框
				where: '',
				query: '',
				isAdmin: false
			};
		},
		onShareAppMessage() {
			var pathList = getCurrentPages()
			var path = pathList[pathList.length - 1].route
			return shareMsg.shareMsg({
				title: "AIIT图书馆",
				path: path,
				imageUrl: '/static/img/shareImg.png'
			})
		},
		onLoad() {
			db.collection('uni-id-users').doc(app.globalData.uid).field('role').get().then( res => {
				let userRole = res.result.data[0].role
				if (userRole.indexOf('admin')!=-1) {
					this.isAdmin = true
				}
			})
		},
		methods: {
			/**
			 * 下拉刷新回调函数
			 */
			onPullDownRefresh() {
				this.tipShow = true
				this.formData.status = 'more'
				this.$refs.udb.loadData({
					clear: true
				}, () => {
					this.tipShow = false
					uni.stopPullDownRefresh()
				})
			},
			/**
			 * 上拉加载回调函数
			 */
			onReachBottom() {
				this.$refs.udb.loadMore()
			},
			load(data, ended) {
				if (ended) {
					this.formData.status = 'noMore'
				}
			},
			getWhere() {
			    const query = this.query.trim()
			    if (!query) {
			        return ''
			    }
			    const queryRe = `/${query}/i`
			    return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			
			async search() {
			    const newWhere = await this.getWhere()
			    const isSameWhere = newWhere === this.where
			    this.where = newWhere
			    if (isSameWhere) { // 相同条件时，手动强制刷新
			        this.$refs.udb.loadData()
			    }
			},
			
			gotoAddBooks: function(){
				uni.navigateTo({
					url: "/pages/library/scanBooks/scanBooks"
				})
			}
		}
	};
</script>

<style lang="scss">
	@import '@/common/uni-ui.scss';

	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #efeff4;
		min-height: 100%;
		height: auto;
	}

	.tips {
		color: #67c23a;
		font-size: 14px;
		line-height: 40px;
		text-align: center;
		background-color: #f0f9eb;
		height: 0;
		opacity: 0;
		transform: translateY(-100%);
		transition: all 0.3s;
	}

	.tips-ani {
		transform: translateY(0);
		height: 40px;
		opacity: 1;
	}

	.shop {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.shop-picture {
		width: 110px;
		height: 110px;
	}

	.shop-picture-column {
		width: 100%;
		height: 170px;
		margin-bottom: 10px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.shop-price {
		margin-top: 5px;
		font-size: 12px;
		color: #ff5a5f;
	}

	.shop-price-text {
		font-size: 16px;
	}

	.hot-tag {
		background: #ff5a5f;
		border: none;
		color: #fff;
	}

	.button-box {
		height: 30px;
		line-height: 30px;
		font-size: 12px;
		background: #007AFF;
		color: #fff;
	}

	.uni-link {
		flex-shrink: 0;
	}

	.ellipsis {
		display: flex;
		overflow: hidden;
	}

	.uni-ellipsis-1 {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.uni-ellipsis-2 {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
	
	.order_icon {
		position: absolute;
		top: 5px;
		left: 0;
		width: 170px;
		height: 170px;
		background-color: grey;
		opacity: 0.7;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.order_icon .text{
		font-size: 50rpx;
		opacity: 1;
		color: white;
	}

	// 默认加入 scoped ，所以外面加一层提升权重
	.list {
		.uni-list--waterfall {

			/* #ifndef H5 || APP-VUE */
			// 小程序 编译后会多一层标签，而其他平台没有，所以需要特殊处理一下
			/deep/ .uni-list {
				/* #endif */
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				padding: 5px;
				box-sizing: border-box;

				/* #ifdef H5 || APP-VUE */
				// h5 和 app-vue 使用深度选择器，因为默认使用了 scoped ，所以样式会无法穿透
				/deep/
				/* #endif */
				.uni-list-item--waterfall {
					width: 50%;
					box-sizing: border-box;

					.uni-list-item__container {
						padding: 5px;
						flex-direction: column;
					}
				}

				/* #ifndef H5 || APP-VUE */
			}

			/* #endif */
		}
	}
</style>
